﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LEDShow.ViewModels;
using LEDShow.Models;
using System.Windows.Threading;
using System.Windows.Media.Animation;
using LEDShow.Helpers;
using System.Threading;
using DotNetSpeech;

namespace LEDShow
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : Window
    {
        private MainViewModel viewModel = null;
        SpVoice voice = new SpVoice();

        int LINE_WIDTH = 26;

        public MainView()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            Helpers.LEDShowGlobalvariables.globalvariables.log.writeInfo("==============================程序启动==============================");
            viewModel = new MainViewModel(this);
            this.Title = "沈阳乘务排班" + viewModel.GetVersion();
            this.DataContext = viewModel;
        }



        /// <summary>
        /// 根据通知等级设计字体颜色
        /// </summary>
        /// <param name="level">通知等级：2.紧急，1.重要，0.正常</param>
        /// <returns></returns>
        private Brush GetColor(int level)
        {
            if (level == 2)
            {
                return Brushes.Red;
            }
            else if (level == 1)
            {
                return Brushes.Green;
            }
            else
            {
                return Brushes.Black;
            }
        }
        private void NextDuty_Button_Click(object sender, RoutedEventArgs e)
        {
            viewModel.Fun_Pager(2, Convert.ToInt32(((sender as Button).DataContext as LEDShow.Models.Page).Name));
        }

        private void OnDuty_Button_Click(object sender, RoutedEventArgs e)
        {
            viewModel.Fun_Pager(1, Convert.ToInt32(((sender as Button).DataContext as LEDShow.Models.Page).Name));
        }

        //车场当班人员页码点击事件
        private void OnDutyDriver_Button_Click(object sender, RoutedEventArgs e)
        {
            viewModel.Fun_Pager(3, Convert.ToInt32(((sender as Button).DataContext as LEDShow.Models.Page).Name));
        }


        //车场即将出勤人员页码点击事件
        private void NextDutyDriver_Button_Click(object sender, RoutedEventArgs e)
        {
            viewModel.Fun_Pager(4, Convert.ToInt32(((sender as Button).DataContext as LEDShow.Models.Page).Name));
        }
        /// <summary>
        /// 设置出勤文字提醒
        /// </summary>
        /// <param name="content"></param>
        /// <param name="later"></param>
        /// <param name="drvier"></param>
        public void SetAttendanceRemind(string content, string later, string drvier, int level, int fontsize)
        {
            int leg = later.Split(' ').Length + drvier.Split(' ').Length + content.Length / 30;

            Paragraph pg = new Paragraph();
            pg.Inlines.Add(GetRTBRun(GetColor(level), fontsize, new FontFamily("楷体"), FontWeights.Bold, content));

            pg.Inlines.Add(GetRTBRun(Brushes.Red, fontsize, new FontFamily("楷体"), FontWeights.Bold, later));

            pg.Inlines.Add(GetRTBRun(Brushes.Blue, fontsize, new FontFamily("楷体"), FontWeights.Bold, drvier));

            rtb_warn.Document = new FlowDocument(pg);

            ThicknessAnimation ta = new ThicknessAnimation();
            ta.From = new Thickness(0, Stack_DutyNotify.ActualHeight, 0, 0);            //起始值
            ta.To = new Thickness(0, -rtb_warn.ActualHeight - leg * 20, 0, 0);        //结束值
            //ta.RepeatBehavior = RepeatBehavior.Forever;                 //循环滚动

            if (leg < 15)
            {
                leg = 15;
            }
            //循环滚动
            //现在暂时是根据行数设定滚动时间，现粗略判断每行大概7秒
            //以后最好根据字数和停顿进行设置
            ta.Duration = TimeSpan.FromSeconds(leg*7);         //动画持续时间
            ScrollViewer scrollViewer = (ScrollViewer)rtb_warn.Template.FindName("PART_ContentHost", rtb_warn);
            scrollViewer.BeginAnimation(ScrollViewer.MarginProperty, ta);



        }
        /// <summary>
        /// 出勤语音提醒
        /// </summary>
        /// <param name="content"></param>
        /// <param name="later"></param>
        /// <param name="driver"></param>
        public void SpeechAttendanceRemind(string content, string later, string driver)
        {
            try
            {
                //Thread.Sleep(1000 * 6);


                    string info = content + later + driver;
                    voice.Rate = -3;
                    string[] msg = info.Split('\n');
                    for (int i = 0; i < msg.Length; i++)
                    {
                        //Thread.Sleep(500);
                        voice.Speak(msg[i], SpeechVoiceSpeakFlags.SVSFlagsAsync);
                    }


            }
            catch (Exception ex)
            {
                Helpers.LEDShowGlobalvariables.globalvariables.log.writeError(ex.ToString());
            }

        }

        private int GetLineCount(string content,int lineWidth) {
            int result=0;
            int lastIndex = 0;

            if (lineWidth==0)
                throw new Exception("line width must not be 0");
            while (lastIndex<content.Length)
            {
                int index = content.IndexOf('\n',lastIndex+1);


                if (index >= 0)
                {
                    result += (index - lastIndex-1) / lineWidth + 1;
                    lastIndex = index+1;
                }
                else
                {
                    //result = content.Length / lineWidth+1;
                    result += (content.Length - 1 - lastIndex) / lineWidth + 1;
                    break;
                }
            }
            return result;
        }

        public void SetContent(string type, string content, int level, int fontsize)
        {
            
            switch (type)
            {
                case "注意事项":
                    //rtb_zysx.Document = new FlowDocument(new Paragraph(GetRTBRun(GetColor(level), fontsize, new FontFamily("楷体"), FontWeights.Bold, content)));
                    
                   System.IO.StringReader sr = new System.IO.StringReader(content);
                   System.Xml.XmlReader xr = System.Xml.XmlReader.Create(sr);
                   rtb_zysx.Document = (FlowDocument)System.Windows.Markup.XamlReader.Load(xr);
                   ScrollViewer scrollViewer = (ScrollViewer)rtb_zysx.Template.FindName("PART_ContentHost", rtb_zysx);
                   TextRange textRange = new TextRange(rtb_zysx.Document.ContentStart, rtb_zysx.Document.ContentEnd);
                    string text = textRange.Text;
                    int lineCount = GetLineCount(text, LINE_WIDTH);
                    if (lineCount > 5)
                    {
                        //滚动字幕
                        int len = text.Length / 30;
                        ThicknessAnimation ta = new ThicknessAnimation();
                        ta.From = new Thickness(0, Stack_Caution.ActualHeight, 0, 0);            //起始值
                        ta.To = new Thickness(0, -rtb_zysx.ActualHeight - len * 20, 0, 0);        //结束值
                        ta.RepeatBehavior = RepeatBehavior.Forever;                 //循环滚动
                        //if (len < 9)
                        //{
                        string timestr = System.Configuration.ConfigurationManager.AppSettings["ZYSXTime"];
                        if (!string.IsNullOrEmpty(timestr))
                            len = int.Parse(timestr);
                        else
                            len = 9;
                        //}
                        //循环滚动
                        ta.Duration = TimeSpan.FromSeconds(len);         //动画持续时间
                        scrollViewer.BeginAnimation(ScrollViewer.MarginProperty, ta);
                    }
                    else
                    {
                        scrollViewer.BeginAnimation(ScrollViewer.MarginProperty, null);
                    }

                    break;

                case "运营目标":
                    rtb_goal.Document = new FlowDocument(new Paragraph(GetRTBRun(GetColor(level), fontsize, new FontFamily("楷体"), FontWeights.Bold, content)));
                    ScrollViewer sViewer = (ScrollViewer)rtb_goal.Template.FindName("PART_ContentHost", rtb_goal);
                    if (GetLineCount(content, LINE_WIDTH) > 4)
                    {
                        //滚动字幕
                        int length = content.Length / 30;
                        ThicknessAnimation tan = new ThicknessAnimation();
                        tan.From = new Thickness(0, Stack_Target.ActualHeight, 0, 0);            //起始值
                        tan.To = new Thickness(0, -rtb_goal.ActualHeight - length * 20, 0, 0);        //结束值
                        tan.RepeatBehavior = RepeatBehavior.Forever;                 //循环滚动
                        if (length < 9)
                        {
                            length = 9;
                        }
                        //循环滚动
                        tan.Duration = TimeSpan.FromSeconds(length);         //动画持续时间
                        
                        sViewer.BeginAnimation(ScrollViewer.MarginProperty, tan);
                    }
                    else
                    {
                        sViewer.BeginAnimation(ScrollViewer.MarginProperty, null);
                    }

                    break;
            }
        }

        public void SetNotifyContent(string contents, int levels, int fontsizes)
        {
            Run run_str_gs = GetRTBRun(GetColor(levels), fontsizes, new FontFamily("楷体"), FontWeights.UltraBlack, string.Format("\n{0}\n\n", contents));
            Paragraph pg = new Paragraph();
            pg.Inlines.Add(run_str_gs);
            rtb_notify.Document = new FlowDocument(pg);
            ScrollViewer scrollViewer = (ScrollViewer)rtb_notify.Template.FindName("PART_ContentHost", rtb_notify);
            if (GetLineCount(contents, LINE_WIDTH) > 4)
            {
                //滚动字幕
                int leng = contents.Length / 30; ;
                ThicknessAnimation ta = new ThicknessAnimation();
                ta.From = new Thickness(0, Stack_Notify.ActualHeight, 0, 0);      //起始值
                ta.To = new Thickness(0, -rtb_notify.ActualHeight, 0, 0);        //结束值
                ta.RepeatBehavior = RepeatBehavior.Forever;     //循环滚动
                if (leng < 12)
                {
                    leng = 12;
                }
                ta.Duration = TimeSpan.FromSeconds(leng);       //动画持续时间
                
                scrollViewer.BeginAnimation(ScrollViewer.MarginProperty, ta);
                
            }
            else
            {
                scrollViewer.BeginAnimation(ScrollViewer.MarginProperty, null);
            }


        }


        private Run GetRTBRun(Brush foreground, double fontsize, FontFamily fontfamily, FontWeight fontweight, string content)
        {
            Run run = new Run();
            run.Foreground = foreground;
            run.FontSize = fontsize;
            run.FontFamily = fontfamily;
            run.FontWeight = fontweight;
            run.Text = content;

            return run;
        }



        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //1...
            if (null != viewModel.UpdateInfoThread)
            {
                try
                {
                    viewModel.UpdateInfoThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    viewModel.UpdateInfoThread = null;
                }
            }
            //2...
            if (null != viewModel.RunningTrainThread)
            {
                try
                {
                    viewModel.RunningTrainThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    viewModel.RunningTrainThread = null;
                }
            }

            //3...
            if (null != viewModel.UpdateHeadImageThread)
            {
                try
                {
                    viewModel.UpdateHeadImageThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    viewModel.UpdateHeadImageThread = null;
                }
            }
            //4...
            if (null != viewModel.UpdateNotifyThread)
            {
                try
                {
                    viewModel.UpdateNotifyThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    viewModel.UpdateNotifyThread = null;
                }
            }
            //5...
            if (null != viewModel.UpdateWeatherThread)
            {
                try
                {
                    viewModel.UpdateWeatherThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    viewModel.UpdateWeatherThread = null;
                }
            }


            //6...
            if (null != viewModel.UpdateCountDownThread)
            {
                try
                {
                    viewModel.UpdateCountDownThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    viewModel.UpdateCountDownThread = null;
                }
            } 
            //7...
            if (null != viewModel.LoadSoundThread)
            {
                try
                {
                    viewModel.LoadSoundThread.Abort();
                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    viewModel.LoadSoundThread = null;
                }
            }
        }
    }
}
